using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace GSyncConsole
{
    class MergeFile
    {
        private string filename;

        public string Filename
        {
            get { return filename; }
            set { filename = value; }
        }

        public MergeFile(string filename)
        {
            this.Filename = filename;
              
        }

        public void Start()
        {
            // get filename
            Console.WriteLine(filename);
            // total files
            int totalFiles = GetTotalFileCount(filename);

            string mainFilename = GetMainFilename(filename);

            Console.WriteLine("Total files to join: {0}", totalFiles);

            // open the main file writer stream
            FileStream mainFileStream = new FileStream(mainFilename, FileMode.Create);
            BinaryWriter mainFileWriter = new BinaryWriter(mainFileStream);

            for (int i = 1; i <= totalFiles; i++)
            {
                string partFilename = GenerateFilename(i, totalFiles, filename);
                Console.WriteLine(">>>> {0}", partFilename);

                // confirm that file exists

                if (!File.Exists(partFilename))
                {
                    Console.WriteLine("ERROR: File {0} does not exist", Path.GetFileName(partFilename));
                }
                else
                {                    
                    byte[] fileContents = File.ReadAllBytes(partFilename);

                    mainFileWriter.Write(fileContents);
                }
            }

            mainFileWriter.Close();
            mainFileStream.Close();
        }

        private string GetMainFilename(string filename)
        {
            return string.Format("{0}{1}",
                filename.Substring(0, filename.LastIndexOf(".(Part")),
                Path.GetExtension(filename)
            );
            
        }

        private string GenerateFilename(int index, int totalFiles, string filename)
        {
            return string.Format("{0}Part{1}-{2}){3}",
                        filename.Substring(0, filename.LastIndexOf("Part")),
                        index,
                        totalFiles,
                        Path.GetExtension(filename)
                        );

        }
        
        private int GetTotalFileCount(string filename)
        {
            int part1Position = filename.LastIndexOf("Part");
            
            int hyphen = filename.IndexOf('-', part1Position) + 1;
            int partEnd = filename.IndexOf(')', hyphen);
            int totalFiles = Convert.ToInt32(filename.Substring(hyphen, partEnd - hyphen));

            return totalFiles;
        }
              
    }
}

